/**
 * Copyright 2009-2011 xiaonei.com All right reserved.
 * This software is the confidential and proprietary information of Xiaonei.com ("Confidential Information"). 
 * You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you entered into with Xiaonei.com.
 * Create by XiaoNeiAntiSpamTeam
 *
 */

package com.xiaonei.testbookkeeper;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.apache.bookkeeper.client.BKException;
import org.apache.bookkeeper.client.BookKeeper;
import org.apache.bookkeeper.client.LedgerHandle;
import org.apache.bookkeeper.client.LedgerSequence;
import org.apache.zookeeper.KeeperException;

/**
 * @ClassName: AbstractBookKeeper
 * @Description: 抽象的BookKeeper类
 * @author shaohui.liu shaohui.liu@opi-corp.com
 * @date Feb 23, 2010 11:44:07 AM
 * 
 */
public class BookKeeperExample {

    private BookKeeper bookKeeper;

    private String ledgerPassword = "";

    public BookKeeperExample(String hosts) throws KeeperException, IOException,
            InterruptedException, BKException {
        this.bookKeeper = new BookKeeper(hosts);

        LedgerHandle lh = bookKeeper.createLedger(ledgerPassword.getBytes());

        long ledgerId = lh.getId();

        ByteBuffer entry = ByteBuffer.allocate(4);

        List<byte[]> entries = new ArrayList<byte[]>();

        for (int i = 0; i < 10; i++) {
            entry.putInt(i);
            entry.position(0);
            entries.add(entry.array());

            lh.addEntry(entry.array());
        }

        lh.close();

        lh = bookKeeper.openLedger(ledgerId, ledgerPassword.getBytes());

        LedgerSequence ls = lh.readEntries(0, 9);
        int i = 0;
        while (ls.hasMoreElements()) {
            ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++));
            Integer origEntry = origbb.getInt();
            ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry());

            Integer retrEntry = result.getInt();
        }
        lh.close();

    }

}
